package com.feihong.yw189.utils.facetools;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.model.User.UserInfo;
import com.feihong.yw189.utils.UserLoginInfo;
import com.google.gson.Gson;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.LivenessActivity;
import com.megvii.livenesslib.OpenActiviyuCallBackListener;
import com.megvii.livenesslib.util.ConUtil;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;

import java.util.Map;

/**
 * Created by yucheng on 2018/2/6.
 */

public class FaceUtils {

    //人脸识别 ，活体检测 调用方法
    private String uuid = "";
    private String photo = "";
    private String idcard = "";
    private String headPath = "";
    private Activity mContext;
    private UploadAndVerifyFace uploadAndVerifyFace;
    private MyUsualyDialogggg myUsualyDialogggg;
    private final MyUsualyDialog myUsualyDialog;

    private String mRealName;
    private String mIDCardNum;
    public FaceUtils(Activity context, String photo, String idcard, String headPath,String realName) {
        this.mContext = context;
        this.photo = photo;
        this.idcard = idcard;
        this.headPath = headPath;
        mRealName = realName;
        myUsualyDialogggg = new MyUsualyDialogggg(mContext);
        myUsualyDialogggg.setCanceledOnTouchOutside(false);

        myUsualyDialog = new MyUsualyDialog(mContext, R.layout.wait_item);
        myUsualyDialog.setCancelable(false);
        myUsualyDialog.setCanceledOnTouchOutside(false);
    }

    //联网授权  - ------入口
    public void netWorkWarranty() {
        uuid = ConUtil.getUUIDString(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(mContext);
                LivenessLicenseManager licenseManager = new LivenessLicenseManager(mContext);
                manager.registerLicenseManager(licenseManager);

                manager.takeLicenseFromNetwork(uuid);
                if (licenseManager.checkCachedLicense() > 0) {
                    mHandler_Init.sendEmptyMessageDelayed(1, 500);
                } else {
                    mHandler_Init.sendEmptyMessageDelayed(2, 500);
                }
            }
        }).start();
    }

    Handler mHandler_Init = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //成功
                flag = true;

            } else {
                flag = false;
                //联网授权失败！请检查网络或找服务商
            }
        }
    };

    public void jumpActivity() {
        Intent intent = new Intent(mContext, LivenessActivity.class);
        LivenessActivity.setCallBackListener(mCallBack);
        mContext.startActivity(intent);
    }

    private Boolean flag;

    public Boolean isShouQuan() {
        return flag;
    }

    private void showErrorDialog(String str) {
        ToastUtils.showShortToast(mContext, str);
        mContext.finish();
    }

    OpenActiviyuCallBackListener mCallBack = new OpenActiviyuCallBackListener() {
        @Override
        public void callBack(final Bitmap bmp, String delta, Map<String, byte[]> images) {


//            showProgressDialog("正在验证...");
            Log.e("活体检测", "活体检测成功!!! called with: bmp = [" + bmp != null ? "成功" : "失败" + "], delta = [" + delta != null ? "成功" : "失败" + "], images = [" + images != null ? "成功" : "失败" + "]");

            //身份证照片上传结果和活体检测拿出来的照片和身份证照片对比
//上传成功，但是对比
//比对成功
            uploadAndVerifyFace = new UploadAndVerifyFace(mContext, headPath, new UploadCallBack() {
                //身份证照片上传结果和活体检测拿出来的照片和身份证照片对比
                //上传成功，但是对比
                @Override
                public void success(String uploadImageUrl, int result, String faceMessage) {
                    if (myUsualyDialog != null) {
                        myUsualyDialog.cancel();
                    }
                    if (1 == result) {
                        //比对成功  USER_TEL
                        String user_tel = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserTel();
                        App.getApp().getHttpTools().subShiMing(idcard, user_tel, uploadImageUrl, new RequestCallBack() {
                            @Override
                            public void onSuccess(Object result) {
                                try {
                                    Gson gson = new Gson();
                                    UserInfo userInfo = gson.fromJson(result.toString(), UserInfo.class);
                                    if (userInfo.getStatus() == 1) {
                                        UserLoginInfo.getUserLoginInfoInstance().setUserVerifyRealnameSign("1");
                                        UserLoginInfo.getUserLoginInfoInstance().setUserRealName(mRealName);
                                        UserLoginInfo.getUserLoginInfoInstance().setUserIDCardNum(idcard);
                                        mContext.finish();
                                    } else {
                                        showErrorDialog(userInfo.getInfo());
                                    }
                                } catch (Exception e) {
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                try {
                                    if (mContext != null) {
                                        showErrorDialog(mContext.getResources().getString(R.string.connect_sever_error_toast));
                                    }
                                } catch (Exception e) {

                                }
                            }

                            @Override
                            public void onCancelled(Callback.CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });

                    } else {
                        showErrorDialog(faceMessage);
                        // 重新验证弹窗
                        myUsualyDialogggg.show();
                    }
                }

                @Override
                public void error(String error) {
                    if (myUsualyDialog != null) {
                        myUsualyDialog.cancel();
                    }
                    showErrorDialog("图片上传失败！请重试");
                    Log.e("活体检测", "error() called with: error = [" + error + "]");
                }
            });

            uploadAndVerifyFace.initData(bmp, photo, idcard, delta, images);
            myUsualyDialog.show();
            uploadAndVerifyFace.startUpload();//开始上传并身份证照片对比

        }

        @Override
        public void error(String message) {
            Log.e("活体检测", "活体检测失败!!! called with: message = [" + message + "]");
            showErrorDialog("网络或服务器错误:" + message);
        }

        @Override
        public void finish() {
            Log.e("活体检测", "活体检测结束!!!");
        }
    };

    /**
     * 验证失败弹窗
     */
    public class MyUsualyDialogggg extends Dialog {

        public MyUsualyDialogggg(Context context) {
            super(context, R.style.QiaoDaoDialogStyle);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.again_yanzheng_dialog);
            TextView btn = (TextView) findViewById(R.id.again_yanzheng_btn_again);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 重新开始验证
                    cancel();
                }
            });

            Window window = getWindow();
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.CENTER;
            window.setAttributes(params);
        }
    }
}
